<template>
    <div>
        <TableSearch :query="query" :options="searchOpt" :search="handleSearch" />
        <div class="container">
            <TableOperation :columns="columns" :tableData="tableData" :total="page.total" :viewFunc="handleView"
                :delFunc="handleDelete" :page-change="changePage" :editFunc="handleEdit">
                <template #toolbarBtn>
                    <el-button type="warning" :icon="CirclePlusFilled" @click="visible = true">新增</el-button>
                </template>
            </TableOperation>
        </div>
        <el-dialog :title="isEdit ? '编辑' : '新增'" v-model="visible" width="700px" destroy-on-close
            :close-on-click-modal="false" @close="closeDialog">
            <TableEdit :form-data="rowData" :options="options" :edit="isEdit" :update="updateData" @submit="handleSubmit" />
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="system-user">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { CirclePlusFilled } from '@element-plus/icons-vue';
import { User } from '@/types/user';
import { fetchUserData } from '@/api';
import TableOperation from '@/components/table-custom.vue';
import TableEdit from '@/components/table-edit.vue';
import TableDetail from '@/components/table-detail.vue';
import TableSearch from '@/components/table-search.vue';
import { FormOption, FormOptionList } from '@/types/form-option';
import {getAllUser} from "@/api/user";
import dayjs from "dayjs";



// 查询相关
const query = reactive({
    name: '',
});
const searchOpt = ref<FormOptionList[]>([
    { type: 'input', label: '用户名：', prop: 'name' }
])
const handleSearch = () => {
    changePage(1);
};

// 表格相关
let columns = ref([
    { type: 'index', label: '序号', width: 55, align: 'center' },
    { prop: 'username', label: '用户名' },
    { prop: 'companyName', label: '单位名称' },
    { prop: 'password', label: '密码' },
    { prop: 'createdTime', label: '注册时间' },
    { prop: 'region', label: '属地所'},
    { prop: 'operator', label: '操作', width: 250 },
])
const page = reactive({
    index: 1,
    size: 10,
    total: 0,
})
const tableData = ref<User[]>([]);
const getData = async () => {
  try {
    const res = await getAllUser();
    console.log('接口返回数据:', res);
    if (res.data && Array.isArray(res.data.data)) {
      // 格式化时间字段
      tableData.value = res.data.data.map(item => ({
        ...item,
        createdTime: item.createdTime ? dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss') : '未知', // 格式化时间
      }));
      page.total = res.data.data.length; // 更新总条数
    } else {
      console.error('接口返回的数据格式不正确:', res);
      ElMessage.error('数据格式不正确');
    }
  } catch (error) {
    console.error('接口调用失败:', error);
    ElMessage.error('获取数据失败');
  }
};

// 在组件挂载时调用 getData
onMounted(() => {
  getData();
});

const changePage = (val: number) => {
    page.index = val;
    getData();
};

// 新增/编辑弹窗相关
let options = ref<FormOption>({
    labelWidth: '100px',
    span: 12,
    list: [
        { type: 'input', label: '用户名', prop: 'username', required: true },
        { type: 'input', label: '单位名称', prop: 'companyName', required: true },
        { type: 'input', label: '密码', prop: 'password', required: true },
        { type: 'input', label: '注册时间', prop: 'createdTime', required: true },
        { type: 'input', label: '属地所', prop: 'region', required: true },
    ]
})
const visible = ref(false);
const isEdit = ref(false);
const rowData = ref({});

// 新增功能：处理提交
const handleSubmit = (formData: User) => {
  if (isEdit.value) {
    // 编辑逻辑
    const index = tableData.value.findIndex(item => item.id === formData.id);
    if (index !== -1) {
      tableData.value[index] = formData;
    }
  } else {
    // 新增逻辑
    const newUser = {
      ...formData,
      id: Date.now(), // 生成唯一 ID
    };
    tableData.value.unshift(newUser); // 将新数据添加到表格的最前面
  }
  closeDialog();
};

const handleEdit = (row: User) => {
    rowData.value = { ...row };
    isEdit.value = true;
    visible.value = true;
};


const updateData = () => {
    closeDialog();
    getData();
};

const closeDialog = () => {
    visible.value = false;
    isEdit.value = false;
    rowData.value = {}; // 重置表单数据
};

// 查看详情弹窗相关
const visible1 = ref(false);
const viewData = ref({
    row: {},
    list: []
});
const handleView = (row: User) => {
    viewData.value.row = { ...row }
    viewData.value.list = [
        {
            prop: 'id',
            label: '用户ID',
        },
        {
            prop: 'name',
            label: '用户名',
        },
        {
            prop: 'company_name',
            label: '单位名称',
        },
        {
            prop: 'password',
            label: '密码',
        },
        {
            prop: 'date',
            label: '注册日期',
        },
        {
          prop: 'region',
          label: '属所地',
        },
    ]
    visible1.value = true;
};


// 删除功能
const handleDelete = (row: User) => {
  const index = tableData.value.findIndex(item => item.id === row.id);
  if (index !== -1) {
    tableData.value.splice(index, 1); // 删除对应行
    ElMessage.success('删除成功');
  }
};

</script>

<style scoped></style>